<?php
/**
 * 用户数据处理接口
 * Created by PhpStorm.
 * User: zhongbaitong
 * Date: 2020/5/26
 * Time: 21:12
 */

namespace app\controller;

use app\service\Uploader;

class User extends Base
{
    /**
     * 非登陆用户不可访问
     * User constructor.
     */
    public function __construct()
    {
        parent::__construct();
        if (!$this->isLogin()) {
            die(json([
                "code" => 0,
                "msg" => config("tips.unlogin_request_err")
            ]));
        }
    }

    /**
     * 修改用户资料
     * @url [post]:/user/edit
     * @input username string  昵称
     * @input avatar   string  头像
     * @input sex      string  性别
     * @input age      string  年龄
     * @input motto    string  个性签名
     * @return false|string
     */
    public function edit()
    {
        $input = $this->getInput(["username", "avatar", "sex", "age", "motto"]);
        $rs = db("user")->_where(["id", "=", $this->user["id"]])
            ->_update([
                "username" => $input["username"],
                "avatar" => $input["avatar"],
                "sex" => $input["sex"],
                "age" => $input["age"],
                "motto" => $input["motto"],
            ]);
        if (!$rs) {
            return $this->apiError(config("tips.edit_info_err"));
        }
        $user_info = (new Account())->toGetUserInfoById($this->user["id"]);
        return $this->apiSuccess("修改成功",compact("user_info"));
    }

    /**
     * 上传图片接口
     * @url [post]:/user/upload
     * @input file FormData  资源
     * @return false|string
     */
    public function upload()
    {
        $input = $this->getInput();
        $from = $input["from"] ?? "default";
        switch ($from){
            case "avatar":
                $params = [
                    "path" => "./upload/user/avatar/",
                    "prefix" => $this->user["id"] . "_" . date("Y_m_d_")
                ];
                break;
            case "feedback":
                $params = [
                    "path" => "./upload/feedback/",
                    "prefix" => $this->user["id"] . "_" . date("Y_m_d_")
                ];
                break;
            default:
                $params = [
                    "path" => "./upload/default/",
                    "prefix" => date("Y_m_d_")
                ];
        }

        $uploader = new Uploader($params);

        if (!$path = $uploader->go("file")) {
            return $this->apiError($uploader->getErrorInfo());
        }

        return $this->apiReturn(get_domain() . $path);
    }

    /**
     * 检测是否唯一用户名
     * @url [get]:/user/upload
     * @input username string  昵称
     * @return boolean
     */
    public function checkUniqueUserName()
    {
        $input = $this->getInput("username");

        $user = db("user")->_where(["username", "=", $input["username"]])
            ->_where(["id", "!=", $this->user["id"]])
            ->_find();

        return $this->apiReturn((bool)$user);
    }


    /**
     * 收藏资源处理
     * @url [get]:/user/collectHandle
     * @input resource_id int 资源id
     * @return false|string
     */
    public function collectHandle()
    {
        $input = $this->getInput("resource_id");

        $data = [
            "user_id" => $this->user["id"],
            "resource_id" => $input["resource_id"]
        ];
        $rs = db("user_collection")->_where($data)->_find();

        if ($rs) {
            // 已存在：删除
            if (db("user_collection")->_where($data)->_delete()) {
                return $this->apiSuccess(config("tips.uncollect_ok"), [], 2);
            }
        } else {
            // 不存在：插入
            if (db("user_collection")->_insert($data)) {
                return $this->apiSuccess(config("tips.collect_ok"));
            }
        }

        return $this->apiError(config("tips.fail"));
    }

    /**
     * 清空收藏
     * @url [get]:/user/clearCollect
     * @return false|string
     */
    public function clearCollect(){
        db("user_collection")->_where(["user_id"=>$this->user["id"]])
            ->_delete();
        return $this->apiSuccess(config("tips.clear_collect_ok"));
    }


    /**
     * 用户反馈
     * @url [post]:/user/feedback
     * @input content  string  内容
     * @input imgUrls  array   多图
     */
    public function feedback(){
        $input = $this->getInput();

        $content = $input["content"] ?? "";
        $img_urls = $input["img_urls"] ?? [];
        if(!$content && !$img_urls){
            return $this->apiError(config("tips.input_null_err"));
        }

        $rs = db("user_feedback")->_insert([
            "user_id" => $this->user["id"] ?? 0,
            "content" => $content,
            "img_urls" => json_encode($img_urls),
            "client_ip" => get_client_ip()
        ]);

        if(!$rs){
            return $this->apiError();
        }
        return $this->apiSuccess();
    }
}